import React, { createContext, useContext, useState, useEffect } from 'react';

// 用户上下文
const UserContext = createContext();

// 用户角色和权限定义
const USER_ROLES = {
  'esg-director': {
    name: 'ESG总监',
    level: 5,
    permissions: ['*'], // 所有权限
    modules: ['dashboard', 'carbon', 'workbench', 'compliance', 'supply-chain', 'reporting']
  },
  'carbon-manager': {
    name: '碳足迹管理员',
    level: 4,
    permissions: ['carbon:*', 'reporting:carbon', 'dashboard:view'],
    modules: ['dashboard', 'carbon', 'reporting']
  },
  'product-manager': {
    name: '产品经理',
    level: 4,
    permissions: ['workbench:*', 'dashboard:view'],
    modules: ['dashboard', 'workbench']
  },
  'compliance-officer': {
    name: '合规专员',
    level: 3,
    permissions: ['compliance:*', 'reporting:compliance', 'dashboard:view'],
    modules: ['dashboard', 'compliance', 'reporting']
  },
  'supply-chain-manager': {
    name: '供应链管理员',
    level: 3,
    permissions: ['supply-chain:*', 'carbon:suppliers', 'dashboard:view'],
    modules: ['dashboard', 'supply-chain', 'carbon']
  },
  'analyst': {
    name: '数据分析师',
    level: 2,
    permissions: ['dashboard:view', 'reporting:view', 'carbon:view'],
    modules: ['dashboard', 'reporting', 'carbon']
  },
  'operator': {
    name: '操作员',
    level: 1,
    permissions: ['dashboard:view', 'carbon:input'],
    modules: ['dashboard', 'carbon']
  }
};

// 权限检查函数
const hasPermission = (userRole, permission) => {
  const role = USER_ROLES[userRole];
  if (!role) return false;
  
  // 超级权限
  if (role.permissions.includes('*')) return true;
  
  // 检查具体权限
  return role.permissions.some(p => {
    if (p === permission) return true;
    if (p.endsWith(':*') && permission.startsWith(p.slice(0, -1))) return true;
    return false;
  });
};

// 用户状态提供者
export const UserProvider = ({ children }) => {
  const [currentUser, setCurrentUser] = useState({
    id: 'user-001',
    name: '张总监',
    email: 'zhang.director@company.com',
    role: 'esg-director',
    avatar: '/api/placeholder/40/40',
    department: 'ESG部门',
    joinDate: '2023-01-15',
    preferences: {
      theme: 'light',
      language: 'zh-CN',
      notifications: {
        email: true,
        push: true,
        sms: false
      },
      dashboard: {
        layout: 'grid',
        modules: ['carbon', 'compliance', 'supply-chain', 'reporting']
      }
    },
    lastLogin: new Date().toISOString()
  });

  const [teamMembers] = useState([
    {
      id: 'user-002',
      name: '李环保',
      email: 'li.carbon@company.com',
      role: 'carbon-manager',
      department: 'ESG部门',
      status: 'online',
      avatar: '/api/placeholder/40/40'
    },
    {
      id: 'user-003',
      name: '王产品',
      email: 'wang.product@company.com',
      role: 'product-manager',
      department: '产品部',
      status: 'online',
      avatar: '/api/placeholder/40/40'
    },
    {
      id: 'user-004',
      name: '张合规',
      email: 'zhang.compliance@company.com',
      role: 'compliance-officer',
      department: '合规部',
      status: 'away',
      avatar: '/api/placeholder/40/40'
    },
    {
      id: 'user-005',
      name: '赵供应',
      email: 'zhao.supply@company.com',
      role: 'supply-chain-manager',
      department: '采购部',
      status: 'online',
      avatar: '/api/placeholder/40/40'
    },
    {
      id: 'user-006',
      name: '李分析',
      email: 'li.analyst@company.com',
      role: 'analyst',
      department: 'ESG部门',
      status: 'offline',
      avatar: '/api/placeholder/40/40'
    }
  ]);

  // 权限检查
  const checkPermission = (permission) => {
    return hasPermission(currentUser.role, permission);
  };

  // 检查是否可以访问模块
  const canAccessModule = (moduleId) => {
    const role = USER_ROLES[currentUser.role];
    return role && role.modules.includes(moduleId);
  };

  // 获取用户角色信息
  const getUserRole = () => {
    return USER_ROLES[currentUser.role];
  };

  // 更新用户偏好
  const updatePreferences = (newPreferences) => {
    setCurrentUser(prev => ({
      ...prev,
      preferences: {
        ...prev.preferences,
        ...newPreferences
      }
    }));
  };

  // 模拟登录
  const login = (userData) => {
    setCurrentUser({
      ...userData,
      lastLogin: new Date().toISOString()
    });
  };

  // 模拟登出
  const logout = () => {
    setCurrentUser(null);
  };

  // 获取团队成员
  const getTeamMembers = () => {
    return teamMembers;
  };

  // 获取在线成员
  const getOnlineMembers = () => {
    return teamMembers.filter(member => member.status === 'online');
  };

  // 根据角色获取成员
  const getMembersByRole = (role) => {
    return teamMembers.filter(member => member.role === role);
  };

  const value = {
    currentUser,
    teamMembers,
    checkPermission,
    canAccessModule,
    getUserRole,
    updatePreferences,
    login,
    logout,
    getTeamMembers,
    getOnlineMembers,
    getMembersByRole
  };

  return (
    <UserContext.Provider value={value}>
      {children}
    </UserContext.Provider>
  );
};

// 使用用户信息的Hook
export const useUser = () => {
  const context = useContext(UserContext);
  if (!context) {
    throw new Error('useUser must be used within a UserProvider');
  }
  return context;
};

// 权限保护组件
export const PermissionGuard = ({ permission, children, fallback = null }) => {
  const { checkPermission } = useUser();
  
  if (!checkPermission(permission)) {
    return fallback || (
      <div className="p-4 bg-red-50 border border-red-200 rounded-lg">
        <p className="text-red-700">您没有访问此功能的权限</p>
      </div>
    );
  }
  
  return children;
};

// 模块访问保护组件
export const ModuleGuard = ({ moduleId, children, fallback = null }) => {
  const { canAccessModule } = useUser();
  
  if (!canAccessModule(moduleId)) {
    return fallback || (
      <div className="p-4 bg-yellow-50 border border-yellow-200 rounded-lg">
        <p className="text-yellow-700">您的角色无法访问此模块</p>
      </div>
    );
  }
  
  return children;
};

// 用户角色标签组件
export const UserRoleBadge = ({ role, className = '' }) => {
  const roleInfo = USER_ROLES[role];
  
  if (!roleInfo) return null;
  
  const levelColors = {
    5: 'bg-purple-100 text-purple-800',
    4: 'bg-blue-100 text-blue-800',
    3: 'bg-green-100 text-green-800',
    2: 'bg-yellow-100 text-yellow-800',
    1: 'bg-gray-100 text-gray-800'
  };
  
  return (
    <span className={`inline-flex items-center px-2.5 py-0.5 rounded-full text-xs font-medium ${levelColors[roleInfo.level]} ${className}`}>
      {roleInfo.name}
    </span>
  );
};

// 团队成员状态组件
export const UserStatus = ({ status, className = '' }) => {
  const statusConfig = {
    online: { color: 'bg-green-400', label: '在线' },
    away: { color: 'bg-yellow-400', label: '离开' },
    busy: { color: 'bg-red-400', label: '忙碌' },
    offline: { color: 'bg-gray-400', label: '离线' }
  };
  
  const config = statusConfig[status] || statusConfig.offline;
  
  return (
    <div className={`flex items-center ${className}`}>
      <div className={`w-2 h-2 rounded-full ${config.color} mr-2`} />
      <span className="text-xs text-gray-500">{config.label}</span>
    </div>
  );
}; 